/**********************************************************************************
  Snes9x - Portable Super Nintendo Entertainment System (TM) emulator.

  (c) Copyright 1996 - 2002  Gary Henderson (gary.henderson@ntlworld.com),
                             Jerremy Koot (jkoot@snes9x.com)

  (c) Copyright 2002 - 2004  Matthew Kendora

  (c) Copyright 2002 - 2005  Peter Bortas (peter@bortas.org)

  (c) Copyright 2004 - 2005  Joel Yliluoma (http://iki.fi/bisqwit/)

  (c) Copyright 2001 - 2006  John Weidman (jweidman@slip.net)

  (c) Copyright 2002 - 2006  funkyass (funkyass@spam.shaw.ca),
                             Kris Bleakley (codeviolation@hotmail.com)

  (c) Copyright 2002 - 2007  Brad Jorsch (anomie@users.sourceforge.net),
                             Nach (n-a-c-h@users.sourceforge.net),
                             zones (kasumitokoduck@yahoo.com)

  (c) Copyright 2006 - 2007  nitsuja


  BS-X C emulator code
  (c) Copyright 2005 - 2006  Dreamer Nom,
                             zones

  C4 x86 assembler and some C emulation code
  (c) Copyright 2000 - 2003  _Demo_ (_demo_@zsnes.com),
                             Nach,
                             zsKnight (zsknight@zsnes.com)

  C4 C++ code
  (c) Copyright 2003 - 2006  Brad Jorsch,
                             Nach

  DSP-1 emulator code
  (c) Copyright 1998 - 2006  _Demo_,
                             Andreas Naive (andreasnaive@gmail.com)
                             Gary Henderson,
                             Ivar (ivar@snes9x.com),
                             John Weidman,
                             Kris Bleakley,
                             Matthew Kendora,
                             Nach,
                             neviksti (neviksti@hotmail.com)

  DSP-2 emulator code
  (c) Copyright 2003         John Weidman,
                             Kris Bleakley,
                             Lord Nightmare (lord_nightmare@users.sourceforge.net),
                             Matthew Kendora,
                             neviksti


  DSP-3 emulator code
  (c) Copyright 2003 - 2006  John Weidman,
                             Kris Bleakley,
                             Lancer,
                             z80 gaiden

  DSP-4 emulator code
  (c) Copyright 2004 - 2006  Dreamer Nom,
                             John Weidman,
                             Kris Bleakley,
                             Nach,
                             z80 gaiden

  OBC1 emulator code
  (c) Copyright 2001 - 2004  zsKnight,
                             pagefault (pagefault@zsnes.com),
                             Kris Bleakley,
                             Ported from x86 assembler to C by sanmaiwashi

  SPC7110 and RTC C++ emulator code
  (c) Copyright 2002         Matthew Kendora with research by
                             zsKnight,
                             John Weidman,
                             Dark Force

  S-DD1 C emulator code
  (c) Copyright 2003         Brad Jorsch with research by
                             Andreas Naive,
                             John Weidman

  S-RTC C emulator code
  (c) Copyright 2001-2006    byuu,
                             John Weidman

  ST010 C++ emulator code
  (c) Copyright 2003         Feather,
                             John Weidman,
                             Kris Bleakley,
                             Matthew Kendora

  Super FX x86 assembler emulator code
  (c) Copyright 1998 - 2003  _Demo_,
                             pagefault,
                             zsKnight,

  Super FX C emulator code
  (c) Copyright 1997 - 1999  Ivar,
                             Gary Henderson,
                             John Weidman

  Sound DSP emulator code is derived from SNEeSe and OpenSPC:
  (c) Copyright 1998 - 2003  Brad Martin
  (c) Copyright 1998 - 2006  Charles Bilyue'

  SH assembler code partly based on x86 assembler code
  (c) Copyright 2002 - 2004  Marcus Comstedt (marcus@mc.pp.se)

  2xSaI filter
  (c) Copyright 1999 - 2001  Derek Liauw Kie Fa

  HQ2x, HQ3x, HQ4x filters
  (c) Copyright 2003         Maxim Stepin (maxim@hiend3d.com)

  Win32 GUI code
  (c) Copyright 2003 - 2006  blip,
                             funkyass,
                             Matthew Kendora,
                             Nach,
                             nitsuja

  Mac OS GUI code
  (c) Copyright 1998 - 2001  John Stiles
  (c) Copyright 2001 - 2007  zones


  Specific ports contains the works of other authors. See headers in
  individual files.


  Snes9x homepage: http://www.snes9x.com

  Permission to use, copy, modify and/or distribute Snes9x in both binary
  and source form, for non-commercial purposes, is hereby granted without
  fee, providing that this license information and copyright notice appear
  with all copies and any derived work.

  This software is provided 'as-is', without any express or implied
  warranty. In no event shall the authors be held liable for any damages
  arising from the use of this software or it's derivatives.

  Snes9x is freeware for PERSONAL USE only. Commercial users should
  seek permission of the copyright holders first. Commercial use includes,
  but is not limited to, charging money for Snes9x or software derived from
  Snes9x, including Snes9x or derivatives in commercial game bundles, and/or
  using Snes9x as a promotion for your commercial product.

  The copyright holders request that bug fixes and improvements to the code
  should be forwarded to them so everyone can benefit from the modifications
  in future versions.

  Super NES and Super Nintendo Entertainment System are trademarks of
  Nintendo Co., Limited and its subsidiary companies.
**********************************************************************************/

/**********************************************************************************
  Snes9x GTK Port
  
  (c) Copyright 2007 - 2008  Brandon Wright (bearoso@gmail.com)
**********************************************************************************/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlwriter.h>
#include <gdk/gdkx.h>
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <gdk/gdkkeysyms.h>
#include <glade/glade-build.h>

#include "gtk_config.h"
#include "gtk_s9x.h"
#include "gtk_sound.h"

char *
get_config_dir (void)
{
    char *homedir, *configdir;
    
    /* Find config directory */
    homedir = getenv ("HOME");
    
    if (!homedir)
    {
        configdir = strdup (".snes9x");
    }
    else
    {
        configdir =  (char *) malloc (strlen (homedir) + 9);
        sprintf (configdir, "%s/.snes9x", homedir);
    }
    
    return configdir;
}

char *
get_config_file_name (void)
{
    char *filename;
    
    filename = get_config_dir ();
    
    filename = (char *) realloc (filename, strlen (filename) + 12);
    strcat (filename, "/snes9x.xml");
    
    return filename;
}

static void
xml_out_string (xmlTextWriterPtr xml, const char *name, const char *value)
{   
    xmlTextWriterStartElement (xml, BAD_CAST "option");
    xmlTextWriterWriteAttribute (xml, BAD_CAST "name", BAD_CAST name);
    xmlTextWriterWriteAttribute (xml, BAD_CAST "value", BAD_CAST value);
    xmlTextWriterEndElement (xml);
}

static void
xml_out_int (xmlTextWriterPtr xml, const char *name, int value)
{
    char string[256];
    snprintf (string, 1024, "%d", value);
    
    xmlTextWriterStartElement (xml, BAD_CAST "option");
    xmlTextWriterWriteAttribute (xml, BAD_CAST "name", BAD_CAST name);
    xmlTextWriterWriteAttribute (xml, BAD_CAST "value", BAD_CAST string);
    xmlTextWriterEndElement (xml);
}

static void
xml_out_binding (xmlTextWriterPtr xml, const char *name, unsigned int value)
{
    char string[256];
    snprintf (string, 1024, "%u", value);
    
    xmlTextWriterStartElement (xml, BAD_CAST "binding");
    xmlTextWriterWriteAttribute (xml, BAD_CAST "name", BAD_CAST name);
    xmlTextWriterWriteAttribute (xml, BAD_CAST "binding", BAD_CAST string);
    xmlTextWriterEndElement (xml);
}

void 
S9xParsePortConfig (ConfigFile &conf, int pass)
{
    return;
}

Snes9xConfig::Snes9xConfig (void)
{     
    /* Fill up XRR size configurables */
    xrr_config = XRRGetScreenInfo (GDK_DISPLAY (), GDK_ROOT_WINDOW ()); 
    xrr_original_size = XRRConfigCurrentConfiguration (xrr_config,
                                                       &xrr_rotation);
    xrr_sizes = XRRConfigSizes (xrr_config, &xrr_num_sizes); 
    
#ifdef USE_JOYSTICK
    joystick = NULL;
    joystick_threshold = 50;
#endif
    audio_stream = NULL;
    
#ifdef USE_OPENGL
    opengl_activated = FALSE;
#endif
    
    /* Load some Snes9x Settings */
    Settings.StopEmulation = TRUE; 
    Settings.JoystickEnabled = TRUE;    
    
    return;
}

int
Snes9xConfig::load_defaults (void)
{
    full_screen_on_open = 0;
    change_display_resolution = 0;
    xrr_index = 0;
    scale_to_fit = 1;
    maintain_aspect_ratio = 0;
    scale_method = 0;
    overscan = 0;
    data_location = DIR_ROM;
    save_sram_after_secs = 0;
    rom_loaded = 0;
    multithreading = 0;
#ifdef USE_OPENGL
    use_opengl = 0;
    bilinear_filter = 0;
    sync_to_vblank = 1;
    use_pbos = 0;
    pbo_format = GL_RGB;
#endif
    
    last_directory[0] = '\0';
    window_width = -1;
    window_height = -1;
    custom_sram_directory[0] = '\0';
    
    /* Snes9X Variables */
    Settings.UpAndDown = TRUE;
    Settings.AutoSaveDelay = 0;
    Settings.SkipFrames = 0;
    Settings.Transparency = TRUE;
    Settings.DisplayFrameRate = FALSE;  
    Settings.APUEnabled = TRUE;
    Settings.NextAPUEnabled = TRUE;
    Settings.SixteenBitSound = TRUE;
    Settings.Stereo = TRUE;
    Settings.ReverseStereo = FALSE;
    Settings.InterpolatedSound = TRUE;
    Settings.SoundEnvelopeHeightReading = TRUE;
    Settings.DisableSoundEcho = FALSE;
    Settings.DisableMasterVolume = FALSE;
    Settings.SoundPlaybackRate = 5;
    Settings.SoundBufferSize = buffer_sizes[Settings.SoundPlaybackRate];
    Settings.AltSampleDecode = 0;
    Settings.SoundSync = 0;
    Settings.DisableHDMA = 0;
    Settings.ShutdownMaster = 0;
    Settings.HDMATimingHack = 100;
    Timings.H_Max = SNES_CYCLES_PER_SCANLINE;
    Timings.HBlankStart = SNES_HBLANK_START_HC;
    Settings.DisableIRQ = false;
    Settings.SoundSkipMethod = 0;
    Settings.FrameTimeNTSC = 16667;
    Settings.FrameTimePAL = 20000;
    Settings.FrameTime = Settings.FrameTimeNTSC;
    ICPU.SavedAtOp = FALSE;
    
    memset (pad, 0, sizeof (JoypadBinding) * NUM_JOYPADS);
    memset (shortcut, 0, sizeof (Binding) * NUM_EMU_LINKS);
    
    return 0;
}

#ifdef USE_JOYSTICK

void
Snes9xConfig::joystick_register_centers (void)
{
    for (int i = 0; joystick[i] != NULL; i++)
        joystick[i]->register_centers ();
    
    return;
}

void
Snes9xConfig::flush_joysticks (void)
{
    int i;
    
    for (i = 0; joystick[i] != NULL; i++)
        joystick[i]->flush ();
    
    return;
}

void
Snes9xConfig::set_joystick_mode (int mode)
{
    int i;
    for (i = 0; joystick[i] != NULL; i++)
        joystick[i]->mode = mode;
    
    return;
}

#endif

int
Snes9xConfig::save_config_file (void)
{
    xmlTextWriterPtr xml;
    char *filename;
    char buffer[256];
    
    filename = get_config_file_name ();
    xml = xmlNewTextWriterFilename (filename, 0);
    free (filename);
    
    xmlTextWriterSetIndent (xml, 1);
    
    xmlTextWriterStartDocument (xml, NULL, NULL, NULL);
    xmlTextWriterStartElement (xml, BAD_CAST "snes9x");
    xmlTextWriterStartElement (xml, BAD_CAST "preferences");
    
    xml_out_int (xml, "full_screen_on_open", full_screen_on_open);
    xml_out_int (xml, "change_display_resolution", change_display_resolution);
    xml_out_int (xml, "video_mode", xrr_index);
    xml_out_int (xml, "scale_to_fit", scale_to_fit);
    xml_out_int (xml, "maintain_aspect_ratio", maintain_aspect_ratio);
    xml_out_int (xml, "scale_method", scale_method);
    xml_out_int (xml, "overscan", overscan);
    xml_out_int (xml, "data_location", data_location);
    xml_out_int (xml, "multithreading", multithreading);
    xml_out_string (xml, "last_directory", last_directory);
    xml_out_string (xml, "custom_sram_directory", custom_sram_directory);
    xml_out_int (xml, "window_width", window_width);
    xml_out_int (xml, "window_height", window_height);
#ifdef USE_OPENGL
    xml_out_int (xml, "use_opengl", use_opengl);
    xml_out_int (xml, "bilinear_filter", bilinear_filter);
    xml_out_int (xml, "sync_to_vblank", sync_to_vblank);
    xml_out_int (xml, "use_pbos", use_pbos);
    xml_out_int (xml, "pbo_format", pbo_format);
#endif
    
#ifdef USE_JOYSTICK
    xml_out_int (xml, "joystick_threshold", joystick_threshold);
#endif
    
    /* Snes9X core-stored variables */
    xml_out_int (xml, "transparency", Settings.Transparency); 
    xml_out_int (xml, "show_frame_rate", Settings.DisplayFrameRate);
    xml_out_int (xml, "frameskip", Settings.SkipFrames);
    xml_out_int (xml, "save_sram_after_secs", Settings.AutoSaveDelay);    
    xml_out_int (xml, "sound_emulation", Settings.APUEnabled);
    xml_out_int (xml, "16bit_sound", Settings.SixteenBitSound);
    xml_out_int (xml, "stereo", Settings.Stereo);
    xml_out_int (xml, "reverse_stereo", Settings.ReverseStereo);
    xml_out_int (xml, "gaussian_interpolation", Settings.InterpolatedSound);
    xml_out_int (xml, "envelope_reading", Settings.SoundEnvelopeHeightReading);
    xml_out_int (xml, "sound_echo", !(Settings.DisableSoundEcho));
    xml_out_int (xml, "master_volume", !(Settings.DisableMasterVolume));
    xml_out_int (xml, "playback_rate", Settings.SoundPlaybackRate);
    xml_out_int (xml, "sound_decoder", Settings.AltSampleDecode);
    xml_out_int (xml, "speedhacks", Settings.ShutdownMaster);
    xml_out_int (xml, "hdma", !(Settings.DisableHDMA));
    
    xmlTextWriterEndElement (xml); /* preferences */
    
    xmlTextWriterStartElement (xml, BAD_CAST "controls");
    
#ifdef USE_JOYSTICK
    for (int i = 0; joystick[i]; i++)
    {
        xmlTextWriterStartElement (xml, BAD_CAST "calibration");
        snprintf (buffer, 256, "%d", i);
        xmlTextWriterWriteAttribute (xml, BAD_CAST "joystick", BAD_CAST buffer);
        
        for (int j = 0; j < joystick[i]->num_axes; j++)
        {
            xmlTextWriterStartElement (xml, BAD_CAST "axis");
            
            snprintf (buffer, 256, "%d", j);
            xmlTextWriterWriteAttribute (xml, BAD_CAST "number", BAD_CAST buffer);
                        
            snprintf (buffer, 256, "%d", joystick[i]->calibration[j].min);
            xmlTextWriterWriteAttribute (xml, BAD_CAST "min", BAD_CAST buffer);
            
            snprintf (buffer, 256, "%d", joystick[i]->calibration[j].max);
            xmlTextWriterWriteAttribute (xml, BAD_CAST "max", BAD_CAST buffer);

            snprintf (buffer, 256, "%d", joystick[i]->calibration[j].center);
            xmlTextWriterWriteAttribute (xml, BAD_CAST "center", BAD_CAST buffer);
            
            xmlTextWriterEndElement (xml); /* axis */
        }
        
        xmlTextWriterEndElement (xml); /* Calibration */
    }
#endif
    
    for (int i = 0; i < NUM_JOYPADS; i++)
    {
        Binding *joypad = (Binding *) &pad[i];
        
        xmlTextWriterStartElement (xml, BAD_CAST "joypad");
        snprintf (buffer, 256, "%d", i);
        xmlTextWriterWriteAttribute (xml, BAD_CAST "number", BAD_CAST buffer);
        
        for (int j = 0; j < NUM_JOYPAD_LINKS; j++)
        {
            xml_out_binding (xml, b_links[j].snes9x_name, joypad[j]);            
        }
        
        xmlTextWriterEndElement (xml); /* joypad */
    }
    
    for (int i = NUM_JOYPAD_LINKS; b_links[i].snes9x_name; i++)
    {
        xml_out_binding (xml, 
                         b_links[i].snes9x_name, 
                         shortcut[i - NUM_JOYPAD_LINKS]);
    }
    
    xmlTextWriterEndElement (xml); /* controls */
    xmlTextWriterEndElement (xml); /* snes9x */
    xmlTextWriterEndDocument (xml);
    
    xmlFreeTextWriter (xml);
    
    return 0;
}

int
Snes9xConfig::set_option (const char *name, const char *value)
{
    if (!strcasecmp (name, "full_screen_on_open"))
    {
        full_screen_on_open = atoi (value);
    }
    else if (!strcasecmp (name, "change_display_resolution"))
    {
        change_display_resolution = atoi (value);
    }
    else if (!strcasecmp (name, "video_mode"))
    {
        xrr_index = atoi (value);
    }
    else if (!strcasecmp (name, "scale_to_fit"))
    {
        scale_to_fit = atoi (value);
    }
    else if (!strcasecmp (name, "maintain_aspect_ratio"))
    {
        maintain_aspect_ratio = atoi (value);
    }
    else if (!strcasecmp (name, "scale_method"))
    {
        scale_method = atoi (value);
    }
    else if (!strcasecmp (name, "multithreading"))
    {
        multithreading = atoi (value);
    }
    else if (!strcasecmp (name, "use_opengl"))
    {
#ifdef USE_OPENGL
        use_opengl = atoi (value);
#endif
    }
    else if (!strcasecmp (name, "bilinear_filter"))
    {
#ifdef USE_OPENGL
        bilinear_filter = atoi (value);
#endif
    }
    else if (!strcasecmp (name, "sync_to_vblank"))
    {
#ifdef USE_OPENGL
        sync_to_vblank = atoi (value);
#endif
    }
    else if (!strcasecmp (name, "use_pbos"))
    {
#ifdef USE_OPENGL
        use_pbos = atoi (value);
#endif
    }
    else if (!strcasecmp (name, "pbo_format"))
    {
#ifdef USE_OPENGL
        pbo_format = atoi (value);
#endif
    }    
    else if (!strcasecmp (name, "joystick_threshold"))
    {
#ifdef USE_JOYSTICK
        joystick_threshold = atoi (value);
#endif
    }
    else if (!strcasecmp (name, "data_location"))
    {
        data_location = atoi (value);
    }
    else if (!strcasecmp (name, "save_sram_after_secs"))
    {
        Settings.AutoSaveDelay = atoi (value);
    }
    else if (!strcasecmp (name, "transparency"))
    {
        Settings.Transparency = atoi (value);
    }
    else if (!strcasecmp (name, "show_frame_rate"))
    {
        Settings.DisplayFrameRate = atoi (value);
    }
    else if (!strcasecmp (name, "frameskip"))
    {
        Settings.SkipFrames = atoi (value);
    }
    else if (!strcasecmp (name, "sound_emulation"))
    {
        Settings.APUEnabled = atoi (value);
        Settings.NextAPUEnabled = Settings.APUEnabled;
    }
    else if (!strcasecmp (name, "16bit_sound"))
    {
        Settings.SixteenBitSound = atoi (value);
    }
    else if (!strcasecmp (name, "stereo"))
    {
        Settings.Stereo = atoi (value);
    }
    else if (!strcasecmp (name, "reverse_stereo"))
    {
        Settings.ReverseStereo = atoi (value);
    }
    else if (!strcasecmp (name, "gaussian_interpolation"))
    {
        Settings.InterpolatedSound = atoi (value);
    }
    else if (!strcasecmp (name, "envelope_reading"))
    {
        Settings.SoundEnvelopeHeightReading = atoi (value);
    }
    else if (!strcasecmp (name, "sound_echo"))
    {
        Settings.DisableSoundEcho = !(atoi (value));
    }
    else if (!strcasecmp (name, "master_volume"))
    {
        Settings.DisableMasterVolume = !(atoi (value));
    }
    else if (!strcasecmp (name, "playback_rate"))
    {
        Settings.SoundPlaybackRate = atoi (value);
        Settings.SoundBufferSize = buffer_sizes[Settings.SoundPlaybackRate];
    }
    else if (!strcasecmp (name, "sound_decoder"))
    {
        Settings.AltSampleDecode = atoi (value);
    }
    else if (!strcasecmp (name, "hdma"))
    {
        Settings.DisableHDMA = !(atoi (value));
    }
    else if (!strcasecmp (name, "speedhacks"))
    {
        Settings.ShutdownMaster = atoi (value);
    }
    else if (!strcasecmp (name, "overscan"))
    {
        overscan = atoi (value);
    }
    else if (!strcasecmp (name, "last_directory"))
    {
        strncpy (last_directory, value, PATH_MAX);
    }
    else if (!strcasecmp (name, "custom_sram_directory"))
    {
        strncpy (custom_sram_directory, value, PATH_MAX);
    }
    else if (!strcasecmp (name, "window_width"))
    {
        window_width = atoi (value);
    }
    else if (!strcasecmp (name, "window_height"))
    {
        window_height = atoi (value);
    }
    else 
    {
        fprintf (stderr, "bad option name: %s\n", name);
        return 1;
    }
    
    return 0;
}

int
Snes9xConfig::parse_option (xmlNodePtr node)
{   
    xmlAttrPtr attr = NULL;
    char *name, *value;
    
    /* Find name string */
    for (attr = node->properties; attr; attr = attr->next)
    {
        if (!xmlStrcasecmp (attr->name, BAD_CAST "name"))
        {
            name = (char *) attr->children->content;
            break;
        }
    }
    
    if (!attr)
        return 1;
    
    /* Find value string */
    for (attr = node->properties; attr; attr = attr->next)
        {
            if (!xmlStrcasecmp (attr->name, BAD_CAST "value"))
            {
                value = (char *) attr->children->content;
                break;
            }
        }
    
    if (!attr)
        return 1;
    
    return set_option (name, value);
}

int
Snes9xConfig::parse_binding (xmlNodePtr node, int joypad_number)
{
    char *name = NULL;
    char *type = NULL;
    Binding b;
    
    for (xmlAttrPtr attr = node->properties; attr; attr = attr->next)
    {
        if (!xmlStrcasecmp (attr->name, BAD_CAST "name"))
            name = (char *) attr->children->content;
        
        else if (!xmlStrcasecmp (attr->name, BAD_CAST "binding"))
            type = (char *) attr->children->content;
    }
    
    b = strtoul (type, NULL, 10);
    
    if (joypad_number > -1 && joypad_number < NUM_JOYPAD_LINKS) 
    {
        for (int i = 0; i < NUM_JOYPAD_LINKS; i++)
        {
            if (!strcasecmp (b_links[i].snes9x_name, name))
            {
                Binding *buttons = (Binding *) &pad[joypad_number];
                
                if (b & BINDING_KEY || b & BINDING_JOY)
                    buttons[i] = b;
                else
                    buttons[i] = 0;
            }           
        }
    }
    else
    {
        for (int i = NUM_JOYPAD_LINKS; b_links[i].snes9x_name; i++)
        {
            if (!strcasecmp (b_links[i].snes9x_name, name))
            {
                if (b & BINDING_KEY || b & BINDING_JOY)
                    shortcut[i - NUM_JOYPAD_LINKS] = b;
                else
                    shortcut[i - NUM_JOYPAD_LINKS] = 0;
                    
            }
        }
    }
        
    return 0;
}

int
Snes9xConfig::parse_joypad (xmlNodePtr node)
{
    int joypad_number = -1;
    xmlAttrPtr attr;
    int retval = 0;
    
    /* Try to read joypad number */
    for (attr = node->properties; attr; attr = attr->next)
    {
        if (!xmlStrcasecmp (attr->name, BAD_CAST "number"))
        {
            joypad_number = atoi ((char *) attr->children->content);
            
            if (joypad_number < 0 || joypad_number > (NUM_JOYPADS - 1))
                return 1;
        }
    }
    
    for (xmlNodePtr i = node->children; i; i = i->next)
    {
        if (!xmlStrcasecmp (i->name, BAD_CAST "binding"))
        {
            retval = parse_binding (i, joypad_number) || retval;
        }
    } 
    
    return retval;
}

#ifdef USE_JOYSTICK

int
Snes9xConfig::parse_axis (xmlNodePtr node, int joynum)
{
    int retval = 0;
    xmlAttrPtr attr;
    
    int number = -1, min = -32767, max = 32767, center = 0;
    
    for (attr = node->properties; attr; attr = attr->next)
    {
        if (!xmlStrcasecmp (attr->name, BAD_CAST "number"))
        {
            number = atoi ((char *) attr->children->content);
        }
        
        else if (!xmlStrcasecmp (attr->name, BAD_CAST "min"))
        {
            min = atoi ((char *) attr->children->content);
        }
        
        else if (!xmlStrcasecmp (attr->name, BAD_CAST "max"))
        {
            max = atoi ((char *) attr->children->content);
        }

        else if (!xmlStrcasecmp (attr->name, BAD_CAST "center"))
        {
            center = atoi ((char *) attr->children->content);
        }
    }
    
    if (number >= 0 && number < joystick[joynum]->num_axes)
    {
        joystick[joynum]->calibration[number].min = min;
        joystick[joynum]->calibration[number].max = max;
        joystick[joynum]->calibration[number].center = center;
    }
    
    return retval;
}

int
Snes9xConfig::parse_calibration (xmlNodePtr node)
{
    xmlAttrPtr attr;
    int joynum = -1;
    int num_joysticks = 0;
    int retval = 0;
    
    for (num_joysticks = 0; joystick[num_joysticks]; num_joysticks++);
    
    for (attr = node->properties; attr; attr = attr->next)
    {
        if (!xmlStrcasecmp (attr->name, BAD_CAST "joystick"))
        {
            joynum = atoi ((char *) attr->children->content);
            
            if (joynum < 0 || joynum >= num_joysticks)
                return 0;
        }
    }
    
    for (xmlNodePtr i = node->children; i; i = i->next)
    {
        if (!xmlStrcasecmp (i->name, BAD_CAST "axis"))
        {
            retval = parse_axis (i, joynum) | retval; 
        }
    }
 
    return retval;
}

#endif

int
Snes9xConfig::parse_preferences (xmlNodePtr node)
{
    xmlNodePtr i = NULL;
    int retval = 0;
    
    for (i = node->children; i; i = i->next)
    {
        if (!xmlStrcasecmp (i->name, BAD_CAST "option"))
            retval = parse_option (i) || retval;
    }
    
    return retval;
}

int
Snes9xConfig::parse_controls (xmlNodePtr node)
{
    int retval = 0;
    
    for (xmlNodePtr i = node->children; i; i = i->next)
    {
        if (!xmlStrcasecmp (i->name, BAD_CAST "joypad"))
            retval = parse_joypad (i) || retval;
        
        if (!xmlStrcasecmp (i->name, BAD_CAST "binding"))
            retval = parse_binding (i, -1) || retval;

#ifdef USE_JOYSTICK
        if (!xmlStrcasecmp (i->name, BAD_CAST "calibration"))
            retval = parse_calibration (i) || retval;
#endif
    }
    
    return retval;
}

int
Snes9xConfig::parse_snes9x (xmlNodePtr node)
{
    xmlNodePtr i = NULL;
    int retval = 0;
    
    if (xmlStrcasecmp (node->name, BAD_CAST "snes9x"))
    {
        fprintf (stderr, "failure to read snes9x node");
        return 1;
    }
    
    for (i = node->children; i; i = i->next)
    {
        if (!xmlStrcasecmp (i->name, BAD_CAST "preferences"))
        {
            retval = parse_preferences (i) || retval;
        }
        
        else if (!xmlStrcasecmp (i->name, BAD_CAST "controls"))
        {
            retval = parse_controls (i) || retval;
        }
    }
    
    return 0;
}

int
Snes9xConfig::load_config_file (void)
{
    struct stat file_info;
    char *pathname;
    xmlDoc *xml_doc = NULL;
    xmlNodePtr xml_root = NULL;
    
    load_defaults ();
    
    pathname = get_config_dir ();
    
    if (stat (pathname, &file_info))
    {
        if (mkdir (pathname, 0))
        {
            fprintf (stderr, 
                     "Couldn't create config directory: %s\n", 
                     pathname);
            return -1;
        }
    }
    
    free (pathname);
    
    pathname = get_config_file_name ();
    
    if (stat (pathname, &file_info))
    {
        save_config_file ();        
    }
    
    xml_doc = xmlReadFile (pathname, NULL, 0);
    
    if (!xml_doc)
    {
        fprintf (stderr, "Couldn't open config file: %s\n", pathname);
        return -2;
    }
    
    free (pathname);
    
    xml_root = xmlDocGetRootElement (xml_doc);
    
    parse_snes9x (xml_root);
    
    return 0;
}

void
Snes9xConfig::rebind_keys (void)
{
    s9xcommand_t cmd;
    char buf[256];
    
    S9xUnmapAllControls ();
    
    for (int joypad_i = 0; joypad_i < NUM_JOYPADS; joypad_i++ )
    {
        Binding *bin = (Binding *) &pad[joypad_i];
        
        for (int button_i = 0; button_i < NUM_JOYPAD_LINKS; button_i++)
        {
            snprintf (buf, 
                      256, 
                      "Joypad%d %s", 
                      joypad_i + 1, 
                      b_links[button_i].snes9x_name);
            
            cmd = S9xGetPortCommandT (buf);
            
            S9xMapButton (bin[button_i] & ~BINDING_THRESHOLD_MASK, cmd, FALSE);
        }
    }
    
    for (int i = NUM_JOYPAD_LINKS; b_links[i].snes9x_name; i++)
    {
        snprintf (buf, 256, b_links[i].snes9x_name);
        cmd = S9xGetPortCommandT (buf);
        S9xMapButton (shortcut[i - NUM_JOYPAD_LINKS] & ~BINDING_THRESHOLD_MASK, 
                      cmd, 
                      FALSE);
    }
    
    cmd = S9xGetPortCommandT ("Pointer Mouse1+Superscope+Justifier1");
    S9xMapPointer (BINDING_MOUSE_POINTER, cmd, TRUE);
    
    cmd = S9xGetPortCommandT ("{Mouse1 L,Superscope Fire,Justifier1 Trigger}");
    S9xMapButton (BINDING_MOUSE_BUTTON0, cmd, FALSE);
    
    cmd = S9xGetPortCommandT ("{Justifier1 AimOffscreen Trigger,Superscope AimOffscreen}");
    S9xMapButton (BINDING_MOUSE_BUTTON1, cmd, FALSE);
    
    cmd = S9xGetPortCommandT ("{Mouse1 R,Superscope Cursor,Justifier1 Start}");
    S9xMapButton (BINDING_MOUSE_BUTTON2, cmd, FALSE);                            
    
    return;
}

void
Snes9xConfig::reconfigure (void)
{
    rebind_keys ();
    
    return;
}



